
angular.module('U9ImHd.controllers')

    .controller('HomeCtrl', ['$scope', '$ionicSlideBoxDelegate', '$ionicModal', '$ionicHistory', '$state', 'AppManager', 'User', 'Device', 'Help', 'imanDialog', 'APPCONSTANTS', 
        function ($scope, $ionicSlideBoxDelegate, $ionicModal, $ionicHistory, $state, AppManager, User, Device, Help, imanDialog, APPCONSTANTS) {
            $scope.data = {
                user: User.get(),
                minCtHeight: {
                    'height': '380px',
                    'width': '720px'
                }
            };

            $ionicModal.fromTemplateUrl('tpls/sidemenu.html', {
                scope: $scope,
                animation: 'slide-in-right'
            }).then(function(modal) {
                $scope.modal = modal;
            });
            
            $scope.showSideMenu = function () {
                if (Device.isTV()) {
                    return;
                }
                $scope.modal.show();
            };
            $scope.onPagerClick = function (index) {
                $ionicSlideBoxDelegate.slide(index);
            };
            $scope.clickApp = function (app) {
                if (!app.NoWorkStation && !Device.get().WorkLocation) {
                    imanDialog.confirm('请到终端注册界面进行工位绑定', '工位绑定').then(function (btn) {
                        if (btn) {
                            $state.go('register');
                        }
                    });
                    return;
                }
                Help.loadApp(app.AppID).then(function () {
                    $state.go(app.AppID);
                }, function () {
                    imanDialog.toastBottom('加载应用失败，请确认是否已正确安装然后重试。');
                });
            };

            $scope.register = function () {
                $scope.modal.hide().then(function () {
                    $state.go('register');
                });
            };
            $scope.portSetting = function () {
                $scope.modal.hide().then(function () {
                    $state.go('portsetting');
                });
            };
            $scope.connectSetting = function () {
                $scope.modal.hide().then(function () {
                    $state.go('connectsetting');
                });
            };
            $scope.signout = function () {
                $scope.modal.hide().then(function () {
                    User.signout().then(function () {
                        $ionicHistory.nextViewOptions({
                            historyRoot: true,
                            disableAnimate: true,
                            expire: 300
                        });
                        $state.go('login');
                    });
                });
            };
            
            $scope.$on('$destroy', function () {
                $scope.modal.remove();
            });

            var _row = 2, _col = 5, _page = 1,
                _cRow = 0, _cCol = 0, _cPage = 0;
            init();
            
            function init () {
                var formatApp = formatApps(AppManager.getApps());
                $scope.data.appsArray = formatApp.apps;
                _row = formatApp.row;
                _col = formatApp.col;
                _page = formatApp.apps.length;
                supportTV();
            }

            function supportTV () {
                if (!Device.isTV()) {
                    return;
                }
                $scope.data.activeIndex = '' + _cPage + _cRow + _cCol;
                $scope.$on('$ionicView.afterEnter', function () {
                    angular.element(document).keydown(onkeydown);
                });
                $scope.$on('$ionicView.beforeLeave', function () {
                    angular.element(document).off('keydown', onkeydown);
                });
            }

            function onkeydown(event) {
                var keyCode = event.keyCode;
                if (keyCode === 37) { //左
                    if (_cCol > 0) {
                        _cCol--;
                    } else {
                        if (_cPage > 0) {
                            _cPage--;
                            _cCol = _col - 1;
                            $ionicSlideBoxDelegate.slide(_cPage);
                        }
                    }
                    $scope.data.activeIndex = '' + _cPage + _cRow + _cCol;
                    $scope.$apply();
                } else if (keyCode === 38) { //上
                    if (_cRow > 0) {
                        _cRow--;
                        $scope.data.activeIndex = '' + _cPage + _cRow + _cCol;
                    } else {
                        $scope.data.activeIndex = 'sideMenuButton';
                    }
                    $scope.$apply();
                } else if (keyCode === 39) { //右
                    if (_cCol < _col - 1) {
                        if (_cRow * _col + _cCol + 1 < $scope.data.appsArray[_cPage].length) {
                            _cCol++;
                        }
                    } else {
                        if (_cPage < _page - 1) {
                            _cPage++;
                            _cRow = 0;
                            _cCol = 0;
                            $ionicSlideBoxDelegate.slide(_cPage);
                        }
                    }
                    $scope.data.activeIndex = '' + _cPage + _cRow + _cCol;
                    $scope.$apply();
                } else if (keyCode === 40) { //下
                    if ($scope.data.activeIndex === 'sideMenuButton') {
                        _cRow = 0;
                        _cCol = 0;
                    } else if (_cRow < _row - 1) {
                        if ((_cRow + 1) * _col + _cCol < $scope.data.appsArray[_cPage].length) {
                            _cRow++;
                        }
                    }
                    $scope.data.activeIndex = '' + _cPage + _cRow + _cCol;
                    $scope.$apply();
                } else if (keyCode === 13) { // 确认
                    if ($scope.data.activeIndex === 'sideMenuButton') {
                        $scope.modal.show();
                    } else {
                        $scope.clickApp($scope.data.appsArray[_cPage][_cRow * _col + _cCol]);
                    }
                }
            }

            function formatApps (apps) {
                var viewContainer = angular.element('.view-container'),
                    maxNum = APPCONSTANTS.appNumPerPage,
                    row = 2, col = 5;
                if (viewContainer.length > 0) {
                    var appWidth = 180,
                        appHeight = 180,
                        deltaWidth = 40,
                        deltaHeight = 130;
                    row = Math.floor((viewContainer.height() - deltaHeight) / appHeight);
                    col = Math.floor((viewContainer.width() - deltaWidth) / appWidth);
                    if (row > 0 && col > 0) {
                        maxNum = row * col;
                        $scope.data.minCtHeight['height'] = appHeight * row + 'px';
                        $scope.data.minCtHeight['width'] = appWidth * col + 'px';
                    }
                } 
                var j = 0,
                    temp = [],
                    results = [],
                    page = 0;
                for (var i in apps) {
                    apps[i].coordinate = '' + page + (Math.floor(i / col) - page * row) + i % col;
                    temp.push(apps[i]);
                    j++;
                    if (j === maxNum) {
                        j = 0;
                        page++;
                        results.push(temp);
                        temp = [];
                    }
                }
                if (apps.length % maxNum !== 0) {
                    results.push(temp);
                }
                return {
                    apps: results,
                    row: row,
                    col: col
                };
            }
        }
    ]);